<?php
declare (strict_types=1);

namespace app\middleware;

use app\exception\ApiException;
use app\handler\ApiErrDesc;
use app\handler\JwtAuth;

class CheckCompantAuth
{
    /**
     * 处理请求
     * @param \think\Request $request
     * @param \Closure $next
     * @return Response
     */
    public function handle($request, \Closure $next)
    {
        $token = $request->header('authorization')?$request->header('authorization'):$request->param('authorization');
        if ($token) {
            // 校验token
            $jwtAuth = JwtAuth::getInstance();
            $jwtAuth->setToken($token);
            if ($jwtAuth->validate() && $jwtAuth->verify()) {
                [$uid, $type] = explode(',', $jwtAuth->getUid());
                if (empty($uid)) throw new ApiException(ApiErrDesc::LOGIN_ERR);
                if($type != 1)throw new ApiException(ApiErrDesc::AUTH_OR_LOGIN_ERR);
                return $next($request);
            } else {
                throw new ApiException(ApiErrDesc::TOKEN_ERR);
            }
        } else {
            throw new ApiException(ApiErrDesc::TOKEN_EMPTY);
        }
    }
}
